package com.ck.ips.controller;

import com.ck.core.annotation.LoginRequired;
import com.ck.core.constant.CharsetConstant;
import com.ck.core.constant.PageConstant;
import com.ck.core.exception.ServiceException;
import com.ck.ips.model.vo.StoreVO;
import com.ck.ips.service.DeviceGroupService;
import com.ck.ips.service.store.StoreService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * @description: 门店controller
 * @author: zhanglei
 * @date: 2019/4/29 14:26
 */

@Controller
@RequestMapping(value = "/store")
public class StoreController extends BaseController{

    private Logger logger = LoggerFactory.getLogger(StoreController.class);

    @Autowired
    private StoreService storeService;

    @Autowired
    private DeviceGroupService deviceGroupService;

    /**
     * 分页获取门店列表
     * @param storeName 门店名称
     * @param status 门店状态
     * @param pageNum 当前页
     * @param pageSize 每页条数
     * @return
     */
    @LoginRequired
    @ResponseBody
    @PostMapping("/list")
    public Object deviceStatisticsData(String storeName, Integer status, Integer pageNum, Integer pageSize){
        if ( pageNum == null ) { pageNum = PageConstant.DEFAULT_PAGE_NUM; }
        if ( pageSize == null ) { pageSize = PageConstant.DEFAULT_PAGE_SIZE;  }
        Page<StoreVO> storeList = storeService.listByPage(storeName, status, pageNum, pageSize);
        PageInfo<StoreVO> pageInfo = new PageInfo<>(storeList);
        return pageInfo;
    }

    /**
     * 新增门店
     * @param storeName 门店名称
     * @param storeFunctionary 门店负责人
     * @param cellPhone 手机号码
     * @param settledPhone 固定电话
     * @param fax 传真
     * @param province 终端位置，省
     * @param city 终端位置，市
     * @param area 终端位置，区
     * @param longitude 经度
     * @param latitude 纬度
     * @param storeAdd 门店详细地址
     * @param storePhoto 门店头像
     * @return
     */
    @LoginRequired
    @ResponseBody
    @PostMapping(value = "/createStore")
    public Object createStore (String storeName, String storeFunctionary,String cellPhone,String settledPhone,String fax, String province, String city, String area, String longitude, String latitude, String storeAdd,String storePhoto, Long coveredPopulation){
        return storeService.createStroe(storeName,storeFunctionary,cellPhone,settledPhone,fax,province,city,area,longitude,latitude,storeAdd,storePhoto,coveredPopulation);
    }


    /**
     * 编辑门店
     * @param storeId 门店id
     * @param storeName 门店名称
     * @param storeFunctionary 门店负责人
     * @param cellPhone 手机号码
     * @param settledPhone 固定电话
     * @param fax 传真
     * @param province 终端位置，省
     * @param city 终端位置，市
     * @param area 终端位置，区
     * @param longitude 经度
     * @param latitude 纬度
     * @param storeAdd 门店详细地址
     * @param storePhoto 门店头像
     * @return
     */
    @LoginRequired
    @ResponseBody
    @PostMapping(value = "/updateStore")
    public Object updateStore (Long storeId, String storeName, String storeFunctionary,String cellPhone,String settledPhone,String fax, String province, String city, String area, String longitude, String latitude, String storeAdd,String storePhoto, Long coveredPopulation){
        return storeService.updateStore(storeId,storeName,storeFunctionary,cellPhone,settledPhone,fax,province,city,area,longitude,latitude,storeAdd,storePhoto,coveredPopulation);
    }

    /**
     * 修改门店状态
     * @param storeId 门店id
     * @param status 门店状态 0-启用 1-禁用
     * @return
     */
    @LoginRequired
    @ResponseBody
    @PostMapping(value = "/updateStatus")
    public Object updateStatus(Long storeId,Integer status){
        return storeService.updateStatus(storeId,status);
    }

    /**
     * 删除门店
     * @param storeId 门店id
     * @return
     */
    @LoginRequired
    @ResponseBody
    @PostMapping(value = "/deleteStore")
    public Object deleteStore(Long storeId){
        //删除门店
        return storeService.deleteStore(storeId);
    }

    /**
     * 下载模板文件
     * @param response
     */
    @GetMapping(value = "/downloadExcel")
    public void  downloadExcel(HttpServletResponse response) {
        try {
            // 读到流中
            InputStream inStream = this.getClass().getResourceAsStream("/static/template/uploadDeviceExcel.xlsx");
            // 设置输出的格式
            response.reset();
            response.setContentType("application/ms-excel");
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("设备导入模板.xlsx", CharsetConstant.UTF8));
            // 循环取出流中的数据
            byte[] b = new byte[200];
            int len;
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            logger.error("下载门店模板失败：" + e.getMessage(), e);
        }
    }

    /**
     * 上传excel为门店绑定终端设备解析
     * @param path 上传的excel文件地址
     * @param storeId 门店id
     * @return
     */
    @LoginRequired
    @ResponseBody
    @PostMapping(value = "/uploadExcelDevice")
    public Object uploadExcelDevice(String path,Long storeId) throws ServiceException {
        return storeService.uploadExcelDevice(path,storeId);
    }

    /**
     * 确定上传excel
     * @param path 上传的excel文件地址
     * @param storeId 门店id
     */
    @LoginRequired
    @ResponseBody
    @PostMapping(value = "/uploadExcelDeviceSure")
    public Object uploadExcelDeviceSure(String path,Long storeId) throws ServiceException {
        return storeService.uploadExcelDeviceSure(path,storeId);
    }

    /**
     * 导出门店excel
     * @param storeName 门店名称
     * @param status 状态
     * @throws IOException
     */
    //@LoginRequired
    @GetMapping(value = "/exportStoreExcel")
    public void exportStoreExcel(String storeName, Integer status, HttpServletResponse response) throws IOException {
        //装入excel表中
        XSSFWorkbook workbook = storeService.getStoreList(storeName, status);
        //准备将Excel的输出流通过response输出到页面下载
        //输出流
        response.setContentType("application/ms-excel");
        response.setCharacterEncoding(CharsetConstant.UTF8);
        //这后面可以设置导出Excel的名称，此例中名为student.xls
        response.addHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("门店列表.xlsx", CharsetConstant.UTF8));
        //刷新缓冲
        response.flushBuffer();
        //workbook将Excel写入到response的输出流中，供页面下载
        workbook.write(response.getOutputStream());
    }

}
